import React, { Component } from 'react';
import {
    View,
    Text,
    Image,
    TextInput,
    TouchableOpacity,
    StyleSheet,
    SafeAreaView,
    Modal,
    ScrollView,
    DeviceEventEmitter,
    FlatList,
    ActivityIndicator
} from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
import Constant from '../../utils/Constant'//全局变量
import HttpUtils from "../../utils/HttpUtils";
import HttpUrls from "../../utils/HttpUrls";
import Header from "../../components/header";
import RechargePop from './RechargePop';
import CommonAlertView from "../common/CommonAlertView";

let navigation = null

let pageSize = 20
let pageNo = 1;
let itemNo = 0;

export default class BondAccountPage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            totalDepositAmount: '',
            freezeAmount: '',
            showRechargePop: false,
            selectFilterType: '',
            selectFilterTypeTitle: '全部',
            recordsList: [],
            isRefresh: false,
            showFoot: 0, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
            //余额充值、余额提现、余额扣款、冻结扣款、车辆交易保证金、买家信用保证金、卖家信用保证金、订单退款
           
            showTypes: [
                { enumType: 'TradeType', code: '', desc: '全部' },
                { enumType: 'TradeType', code: 6, desc: '余额充值' },
                { enumType: 'TradeType', code: 7, desc: '余额提现' },
                { enumType: 'TradeType', code: 8, desc: '余额扣款' },
                { enumType: 'TradeType', code: 10, desc: '冻结扣款' },
                { enumType: 'TradeType', code: 16, desc: '车辆交易保证金' },
                { enumType: 'TradeType', code: 17, desc: '买家信用保证金' },
                { enumType: 'TradeType', code: 18, desc: '卖家信用保证金' },
                { enumType: 'TradeType', code: 12, desc: '订单退款' },
            ],
            showFilterType: false,
            showAlertView: false,
        };
    }

    componentDidMount() {
        // this.getTradeTypeList()
        this.getWalletInfo()
        this.getWalletRecordsInfo(true)
    }

    getWalletInfo() {
        HttpUtils.getRequest(HttpUrls.merchantAccountDetail, { merchantId: Constant.userInfo.merchantId })
            .then((result) => {
                let code = result.code
                if (code == 0) {
                    let data = result.data
                    this.setState({
                        totalDepositAmount: data.depositAccount && data.depositAccount.totalAmount ? parseFloat(data.depositAccount.totalAmount) : 0,
                        freezeAmount: data.depositAccount && data.depositAccount.freezeAmount ? parseFloat(data.depositAccount.freezeAmount) : 0,
                    })
                }
            })
            .catch((error) => {

            });
    }

    refreshData = () => {
        this.getWalletRecordsInfo(true);
    }

    getTradeTypeList() {
        let param = {
            type: 'TradeType'
        }
        HttpUtils.getRequest(HttpUrls.getTradeTypeList, param)
            .then((result) => {
                this.setState({
                    showTypes: this.state.showTypes.concat(result.data)
                })
            })
            .catch((error) => {

            });
    }

    getWalletRecordsInfo(refresh) {
        if (refresh) {
            pageNo = 1;
            itemNo = 0;
            this.setState({ isRefresh: true })
        } else {
            pageNo++;
        }

        let param = {
            pageNo: pageNo,
            pageSize: pageSize,
            merchantId: Constant.userInfo.merchantId,
            orderDate: this.state.consumeDate,
            tradeType: this.state.selectFilterType,
            scope: 'm',
            payChannels: [6,7,8],
            accountType: 2
        }
        HttpUtils.postRequest(HttpUrls.getDpositPayLogList, param)
            .then((result) => {
                if (refresh) {
                    this.setState({ recordsList: [] })
                }
                let data = result.data
                if (data) {
                    let resultList = data.resultList
                    let dataBlob = [];
                    let i = itemNo;
                    if (resultList && resultList != null && resultList.length > 0) {
                        resultList.map(function (item) {
                            dataBlob.push({
                                key: i,
                                value: item,
                            })
                            i++;
                        });
                        itemNo = i;
                        this.setState({
                            recordsList: this.state.recordsList.concat(dataBlob),
                            isRefresh: false,
                            showFoot: 1,
                        });
                        setTimeout(() => {
                            this.setState({
                                showFoot: dataBlob.length >= pageSize ? 0 : 1,
                            })
                            resultList = null;
                            dataBlob = null;
                        }, 200);
                    } else {
                        this.setState({
                            showFoot: 1,
                            isRefresh: false,
                        });
                    }
                } else {
                    this.setState({
                        showFoot: 1,
                        isRefresh: false,
                    });
                }
            })
            .catch((error) => {

            });
    }

    render() {
        navigation = this.props.navigation
        return (
            <View style={styles.container}>
                {/* 顶部导航栏 */}
                <Image style={styles.imgBg} source={require('source/image/fund_account_bg.png')} />
                <View style={styles.layoutContain}>
                    <View style={styles.layoutContain2}>
                        <Header navigation={navigation} Title={'门店保证金'} RightButton={() => this.renderRightButton()} hideSepLine={true} bgColor={'rgba(0,0,0,0)'} ></Header>

                        <View style={{ flex: 1 }}>
                            <FlatList
                                data={this.state.recordsList}
                                renderItem={this.renderItemView.bind(this)}
                                extraData={this.state}
                                ListHeaderComponent={this.renderMoneyDetail.bind(this)}
                                ListFooterComponent={this.renderFooter.bind(this)}
                                onEndReached={this._onEndReached.bind(this)}
                                onEndReachedThreshold={0.2}
                                onRefresh={this.refreshData}
                                refreshing={this.state.isRefresh}
                                ListEmptyComponent={this.renderEmpty.bind(this)}
                            />
                            {this.renderFilterView()}
                        </View>

                        {
                            this.state.showRechargePop ?
                                <RechargePop
                                    accountType={2}
                                    visible={this.state.showRechargePop}
                                    navigation={navigation}
                                    onClose={() => {
                                        this.setState({
                                            showRechargePop: false,
                                        })
                                    }}
                                />
                                :
                                null
                        }

                        {
                            this.state.showAlertView ?
                                <CommonAlertView
                                    title={'暂不支持自动充值，请联系客服进行充值'}
                                    sureDes={'好的'}
                                    sureAction={() => {
                                        this.setState({
                                            showAlertView: false,
                                        }, function () {
                                            navigation.navigate('ContactUs')
                                        })
                                    }}
                                />
                                : null
                        }

                    </View>
                </View>

            </View>
        );
    }

    renderRightButton() {
        return (
            null
            // <TouchableOpacity
            //     activeOpacity={0.8}
            //     onPress={this.rechargeInstructions}>
            //     <View style={styles.rightBox}>
            //         <Text style={styles.rightText}>充值须知</Text>
            //     </View>
            // </TouchableOpacity>
        )
    }

    renderFilterView() {
        if (this.state.showFilterType) {
            return (
                <View style={styles.filterViewBg}>
                    <ScrollView showsVerticalScrollIndicator={false} style={styles.filterTypeBg}>
                        {
                            this.state.showTypes.map((item) => {
                                return (
                                    <TouchableOpacity
                                        activeOpacity={0.8}
                                        style={styles.filterTypeBox}
                                        onPress={() => {
                                            this.setState({
                                                showFilterType: false,
                                                selectFilterType: item.code,
                                                selectFilterTypeTitle: item.desc == '全部' ? '全部类型' : item.desc
                                            }, function () {
                                                this.getWalletRecordsInfo(true);
                                            })
                                        }}
                                    >
                                        <Text style={this.state.selectFilterType == item.code ? styles.filterTypeSelText : styles.filterTypeText}>{item.desc}</Text>
                                        <View style={styles.sepLine} />
                                    </TouchableOpacity>
                                )
                            })
                        }
                    </ScrollView>
                    <TouchableOpacity
                        activeOpacity={1.0}
                        style={{ flex: 1 }}
                        onPress={() => {
                            this.setState({
                                showFilterType: false
                            })
                        }}
                    />
                </View>


            )
        }
    }

    renderEmpty() {
        if (!this.state.isRefresh) {
            return (
                <NoData Desc="暂无数据" style={{ marginTop: gREM(200) }} />
            )
        } else {
            return (
                null
            )
        }
    }

    renderFooter() {
        if (this.state.showFoot === 1 || this.state.recordsList.length == 0) {
            return <View style={{ height: Constant.bottomHeight }} />;
        } else if (this.state.showFoot === 2) {
            return (
                <View style={styles.footer}>
                    <ActivityIndicator size="small" color="#999999" />
                    <Text style={styles.loadMoreTextStyle}>正在加载更多数据...</Text>
                </View>
            );
        } else if (this.state.showFoot === 0) {
            return null;
        }
    }

    _onEndReached() {
        //如果是正在加载中或没有更多数据了，则返回
        if (this.state.showFoot != 0) {
            return null;
        }

        //底部显示正在加载更多数据
        this.setState({ showFoot: 2 });

        this.getWalletRecordsInfo(false);
    }

    renderItemView({ item, index }) {
        return (
            <View key={index} style={[styles.itemContain, { borderBottomLeftRadius: index == this.state.recordsList.length - 1 ? 6 : 0, borderBottomRightRadius: index == this.state.recordsList.length - 1 ? 6 : 0 }]}>
                <View style={[styles.itemContain1, { borderBottomWidth: index < this.state.recordsList.length - 1 ? 0.3 : 0 }]}>
                    <View>
                        <Text style={styles.itemTitleText}>{item.value.tradeTypeName}</Text>
                        <Text style={styles.itemDesText}>{item.value.createTime + ' ' + (item.value.userFullname ? item.value.userFullname : '')}</Text>
                    </View>

                    <View style={styles.desBox}>
                        <Text style={[styles.itemPriceText, { color: item.value.isIncome ? '#F99802' : '#222222' }]}>{item.value.isIncome ? ('+' + (item.value.totalAmountYuan).toFixed(2)) : item.value.totalAmountYuan ? '-' + (item.value.totalAmountYuan).toFixed(2) : ''}</Text>
                        <Text style={styles.itemDesText}>{item.value.payChannelName}</Text>
                    </View>
                </View>
            </View>
        )
    }

    rechargeInstructions = () => {

    }

    renderMoneyDetail() {
        return (
            <View style={{ flexDirection: 'column', width: '100%', paddingHorizontal: 10 }}>
                <View style={styles.moneyDetailContain}>

                    <Text style={{ width: '100%', textAlign: 'center', fontSize: 15, color: '#999999', marginTop: 24 }}>我的余额（元）</Text>

                    <Text style={{ width: '100%', textAlign: 'center', fontSize: 34, color: '#333333', marginTop: 8, fontWeight: 'bold' }}>{(this.state.totalDepositAmount / 100).toFixed(2)}</Text>

                    <View style={styles.priceBox}>
                        <Text style={{ fontSize: 14, color: '#333333' }}>冻结中（元）</Text>
                        <Text style={{ fontSize: 14, color: '#333333' }}>{(this.state.freezeAmount / 100).toFixed(2)}</Text>
                    </View>

                    <TouchableOpacity
                        activeOpacity={0.8}
                        onPress={() => {
                            this.setState({
                                showRechargePop: true,
                            })
                            // this.setState({
                            //     showAlertView: true
                            // })
                        }}
                        style={{ marginTop: 16, marginBottom: 16 }}
                    >
                        <LinearGradient start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }}
                            colors={['#FFEF3A', '#FFDB1B']}
                            style={styles.rechargeBox}>
                            <Text style={styles.rechargeText}>充值</Text>

                        </LinearGradient>
                    </TouchableOpacity>

                </View>
                <View style={[styles.fileterContainer, { borderBottomLeftRadius: this.state.recordsList.length == 0 ? 6 : 0, borderBottomRightRadius: this.state.recordsList.length == 0 ? 6 : 0, }]}>
                    <Text style={styles.fileterTitleText}>账户明细</Text>
                    <TouchableOpacity
                        style={styles.filterBox}
                        onPress={() => {
                            let showFilterType = this.state.showFilterType
                            this.setState({
                                showDatePicker: false,
                                showFilterType: !showFilterType
                            })
                        }}
                    >
                        <Text style={styles.filterText}>{this.state.selectFilterTypeTitle}</Text>
                        <Image style={styles.filterImg} source={require('source/image/comm/down_small_gray.png')}></Image>
                    </TouchableOpacity>
                </View>
            </View>
        )
    }

}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f5f5f5',
    },
    rightBox: {
        height: '100%',
        width: 70,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'flex-end',
    },
    rightText: {
        fontSize: 13,
        color: '#333333',
    },
    imgBg: {
        width: '100%',
        height: 216,
        resizeMode: 'cover',
    },
    layoutContain: {
        position: 'absolute',
        top: 0,
        bottom: 0,
        left: 0,
        right: 0,
    },
    layoutContain2: {
        width: '100%',
        height: '100%',
        flexDirection: 'column'
    },
    moneyDetailContain: {
        width: '100%',
        paddingHorizontal: 12,
        backgroundColor: '#ffffff',
        borderRadius: 6,
        marginTop: 28,
        alignItems: 'center',
    },
    fileterContainer: {
        width: '100%',
        height: 46,
        paddingHorizontal: 12,
        backgroundColor: '#ffffff',
        borderTopLeftRadius: 6,
        borderTopRightRadius: 6,
        marginTop: 10,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
    },
    fileterTitleText: {
        fontSize: 16,
        color: '#333333',
        fontWeight: '500'
    },
    filterBox: {
        flexDirection: 'row',
        alignItems: 'center',
        height: '100%'
    },
    priceBox: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        height: 40,
        width: '100%',
    },
    rechargeBox: {
        width: 143,
        height: 36,
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: 18,
    },
    rechargeText: {
        fontSize: 14,
        color: '#333333',
    },
    itemBox: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        width: '100%',
        height: 46,
        borderBottomColor: '#e4e4e4',
        borderBottomWidth: 0.3
    },
    titleText: {
        fontSize: 14,
        color: '#333333',
    },
    arrowImg: {
        marginLeft: 5,
        width: 15,
        height: 15
    },
    footer: {
        flexDirection: 'row',
        height: 40,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#f6f6f6'
    },
    loadMoreTextStyle: {
        fontSize: 14,
        color: '#999999',
        marginStart: 10,
    },
    itemContain: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        marginLeft: 10,
        marginRight: 10,
        paddingHorizontal: 16,
        backgroundColor: '#fff',
    },
    itemContain1: {
        height: 80,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        width: '100%',
        borderBottomColor: '#e6e6e6',
        borderBottomWidth: 0.5
    },
    itemTitleText: {
        fontSize: 15,
        color: '#222222',
    },
    desBox: {
        flexDirection: 'column',
        alignItems: 'flex-end'
    },
    itemPriceText: {
        fontSize: 18,
        color: '#222222',
        fontWeight: '600'
    },
    itemDesText: {
        color: '#999999',
        fontSize: 12,
        marginTop: 9
    },
    filterViewBg: {
        position: 'absolute',
        top: 0,
        bottom: 0,
        left: 0,
        right: 0,
        backgroundColor: 'rgba(0,0,0,0.5)'
    },
    filterTypeBg: {
        backgroundColor: '#fff',
        maxHeight: 320
    },
    filterTypeBox: {
        width: '100%',
        height: 40,
        justifyContent: 'center',
        alignItems: 'center'
    },
    filterTypeText: {
        color: '#999999',
        fontSize: 14,
    },
    filterTypeSelText: {
        color: '#222222',
        fontSize: 16,
        fontWeight: '500'
    },
    sepLine: {
        position: 'absolute',
        bottom: 0,
        left: 20,
        right: 20,
        height: 0.5,
        backgroundColor: '#E4E4E4'
    },
})